package com.bjfu.gmms;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class MyBatisUtil {

    private static Map<String, SqlSessionFactory> sqlSessionFactoryMap = new HashMap<>();

    static {
        try {
            // 加载 MyBatis 配置文件
            String resource = "mybatis-config.xml";

            // 使用不同的环境（environment）加载不同的数据库连接配置
            InputStream inputStreamDev = Resources.getResourceAsStream(resource);
            sqlSessionFactoryMap.put("development", new SqlSessionFactoryBuilder().build(inputStreamDev, "development"));

            InputStream inputStreamTeacher = Resources.getResourceAsStream(resource);
            sqlSessionFactoryMap.put("teacher", new SqlSessionFactoryBuilder().build(inputStreamTeacher, "teacher"));

            InputStream inputStreamStudent = Resources.getResourceAsStream(resource);
            sqlSessionFactoryMap.put("student", new SqlSessionFactoryBuilder().build(inputStreamStudent, "student"));

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to initialize MyBatis configuration", e);
        }
    }

    // 根据角色返回 SqlSessionFactory
    public static SqlSessionFactory getSqlSessionFactory(String role) {
        return sqlSessionFactoryMap.getOrDefault(role, sqlSessionFactoryMap.get("development"));
    }

    // 获取 SqlSession
    public static SqlSession getSqlSession(String role) {
        return getSqlSessionFactory(role).openSession();
    }
}
